package com.hlyj.http.base.tool.lib_hlyj_base.utils

import android.app.Activity
import android.app.Dialog
import android.graphics.PixelFormat
import android.util.Log
import android.view.Gravity
import android.view.WindowManager
import android.widget.TextView
import com.cszy.mfjx.lib_hlyj_base.R

object SafeDialogUtils {
    private var dialog: Dialog? = null
    private const val MY_PACKAGE_NAME = "com.csgc.camera"



    /**
     * 在第三方Activity显示安全Dialog
     */
    fun showSafeDialog(activity: Activity, message: String) {
        // 只在自己的包Activity不显示
        if (activity::class.java.name.startsWith(MY_PACKAGE_NAME)) {
            return
        }

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        removeSafeDialog()

        try {
            dialog = Dialog(activity, android.R.style.Theme_Translucent_NoTitleBar).apply {
                setContentView(R.layout.custom_bottom_view)
                window?.apply {
                    // 设置布局参数
                    val layoutParams = WindowManager.LayoutParams().apply {
                        // 设置宽高
                        width = WindowManager.LayoutParams.WRAP_CONTENT
                        height = WindowManager.LayoutParams.WRAP_CONTENT

                        // 设置位置 - 底部居中，向上偏移150像素
                        gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
                        y = -150 // 负值表示向上偏移

                        // 设置窗口标志
                        flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        format = PixelFormat.TRANSLUCENT
                    }

                    // 应用布局参数
                    attributes = layoutParams
                }

                findViewById<TextView>(R.id.customText)?.text = message
                setCancelable(false)
                show()
            }
            Log.d("SafeDialog", "Dialog shown in: ${activity::class.java.name}")
        } catch (e: Exception) {
            Log.e("SafeDialog", "Failed to show dialog: ${e.message}")
            removeSafeDialog()
        }
    }

    fun removeSafeDialog() {
        try {
            dialog?.dismiss()
        } catch (e: Exception) {
            Log.e("SafeDialog", "Error dismissing dialog: ${e.message}")
        } finally {
            dialog = null
        }
    }
}